package com.cy.pj.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Controller
public class AjaxController {
    private List<Map<String, String>> list = new ArrayList<>();

    public AjaxController() {
        Map<String, String> map = new HashMap<>();
        map.put("id", "1");
        map.put("name","张三");
        map.put("gender", "男");
        map.put("job", "java程序员");
        list.add(map);
    }

    /**
     * 获取ajax页面
     *
     * localhost:8080/ajaxJs
     *
     * @return
     */
    @RequestMapping("/ajaxJs")
    public String ajaxJs() {
        return "ajax-01";
    }

    @RequestMapping("/ajaxJq")
    public String ajaxJq() {
        return "ajax-02";
    }

    /**
     * 异步GET请求
     * @return
     */
    @RequestMapping("/doAjaxGet")
    @ResponseBody
    public List<Map<String, String>> doAjaxGet() {
        return list;
    }

    /**
     * 异步POST请求
     * @param map
     * @return
     */
    @PostMapping("/doAjaxPost")
    @ResponseBody
    public String doAjaxPost(@RequestParam Map<String, String> map) {
        list.add(map);
        return "submit success";
    }

    /**
     * 异步DELETE请求
     * @param id
     * @return
     */
    @DeleteMapping("/doAjaxDelete")
    @ResponseBody
    public String doAjaxDelete(String id) {
        Iterator<Map<String, String>> iterator = list.iterator();
        Map<String, String> map = null;
        while (iterator.hasNext()) {
            map = iterator.next();
            if (map.get("id").equals(id)) {
                break;
            }
        }
        if (map != null) {
            list.remove(map);
            return "delete success";
        }
        return "delete failed";
    }

    @PutMapping("/doAjaxPut")
    @ResponseBody
    public String doAjaxPut(@RequestParam Map<String, String> map) {
        Iterator<Map<String, String>> iterator = list.iterator();
        Map<String, String> selectedMap = null;
        while (iterator.hasNext()) {
            selectedMap = iterator.next();
            if (selectedMap.get("id").equals(map.get("id"))) break;
        }
        if (selectedMap != null) {
            selectedMap.put("name", map.get("name"));
            selectedMap.put("gender", map.get("gender"));
            selectedMap.put("job", map.get("job"));
            return "update success";
        }
        return "update failed";
    }
}
